package com.example.itemtouchhelper

import android.content.Context
import android.graphics.Canvas
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.itemtouchhelper.utils.ToastUtil
import kotlin.math.abs

/**
 * @author by liliang on 2020/6/2 3:47 AM
 */
class CustomItemTouchCallback(private var itemTouchState: ItemTouchState, private var context: Context) : ItemTouchHelper.Callback() {
    override fun getMovementFlags(recyclerView: RecyclerView,
                                  viewHolder: RecyclerView.ViewHolder): Int {

        // 上下拖动
        val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN

        // 向左滑动
        val swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
                         target: RecyclerView.ViewHolder): Boolean {
        return itemTouchState.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
       itemTouchState.onItemRemove(viewHolder.adapterPosition)
    }

    override fun onChildDraw(c: Canvas, recyclerView: RecyclerView,
                             viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float,
                             actionState: Int, isCurrentlyActive: Boolean) {
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            ToastUtil.showShort(context, "左右滑动")
            viewHolder.itemView.apply {
                alpha = 1.0f - abs(dX) / width.toFloat()
            }
        } else if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            ToastUtil.showShort(context, "上下拖动")
        }
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
    }
}